package com.lzb.findphone.service;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.os.VibratorManager;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UriUtils;
import com.lzb.findphone.R;
import com.lzb.findphone.activity.SoundActivity;
import com.lzb.findphone.basic.media.AudioPlayerImpl;
import com.lzb.findphone.basic.media.IAudioPlayer;
import com.lzb.findphone.bean.SettingBean;
import com.lzb.findphone.utils.AppSpUtils;
import com.lzb.findphone.utils.FlashlightUtils;

public class ClapDetectionService extends Service {
    private static final String CHANNEL_ID = "clap_detection_channel";
    private static final int NOTIFICATION_ID = 101;

    // 音频参数
    private static final int SAMPLE_RATE = 44100;
    private static final int CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO;
    private static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
    private static final int BUFFER_SIZE = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT);

    private AudioRecord audioRecord;
    private boolean isRecording = false;
    private Thread recordingThread;
    private Handler mainHandler;

    // 拍手检测参数
    private static final double CLAP_THRESHOLD = 0.45; // 音量阈值
    private static final int CLAP_DURATION_MS = 200; // 拍手持续时间
    private static final int CLAP_COOLDOWN_MS = 1000; // 检测间隔
    private long lastClapTime = 0;

    private AudioPlayerImpl audioPlayer;
    private Vibrator vibrator;
    private SettingBean settingBean;
    private Handler flashHandler;
    private Runnable flashRunnable;
    private boolean isFlashing = false;
    
    private Handler vibrateHandler;
    private Runnable vibrateRunnable;
    private boolean isVibrating = false;

    @Override
    public void onCreate() {
        super.onCreate();
        mainHandler = new Handler(Looper.getMainLooper());
        audioPlayer = new AudioPlayerImpl();
        audioPlayer.setHasLoop(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            VibratorManager vibratorManager = (VibratorManager) getSystemService(Context.VIBRATOR_MANAGER_SERVICE);
            vibrator = vibratorManager.getDefaultVibrator();
        } else {
            vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        }
        flashHandler = new Handler(Looper.getMainLooper());
        vibrateHandler = new Handler(Looper.getMainLooper());

        createNotificationChannel();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startForeground(NOTIFICATION_ID, createNotification());
        startClapDetection();
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopClapDetection();
        stopFlashing();
        stopVibrating();
        if (audioPlayer != null) {
            audioPlayer.stop();
        }
    }

    @SuppressLint("MissingPermission")
    private void startClapDetection() {
        if (isRecording) return;

        audioRecord = new AudioRecord(
                MediaRecorder.AudioSource.MIC,
                SAMPLE_RATE,
                CHANNEL_CONFIG,
                AUDIO_FORMAT,
                BUFFER_SIZE
        );

        if (audioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
            stopSelf();
            return;
        }

        isRecording = true;
        audioRecord.startRecording();

        recordingThread = new Thread(() -> {
            short[] buffer = new short[BUFFER_SIZE / 2];

            while (isRecording) {
                int read = audioRecord.read(buffer, 0, buffer.length);
                if (read > 0) {
                    processAudioData(buffer, read);
                }
            }
        });

        recordingThread.start();
    }

    private void stopClapDetection() {
        isRecording = false;

        if (audioRecord != null) {
            audioRecord.stop();
            audioRecord.release();
            audioRecord = null;
        }

        if (recordingThread != null) {
            try {
                recordingThread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            recordingThread = null;
        }
    }

    private void processAudioData(short[] buffer, int readSize) {
        // 计算音量
        double volume = calculateVolume(buffer, readSize);


        // 检测拍手
        if (volume > CLAP_THRESHOLD && isValidClap()) {
            // 在calculateVolume中添加调试日志
            Log.e("ClapTrigger", "实时音量: " + String.format("%.3f", volume) +
                    ", 阈值: " + CLAP_THRESHOLD +
                    ", 触发状态: " + (volume > CLAP_THRESHOLD ? "满足" : "不满足"));
            mainHandler.post(this::onClapDetected);
        }
    }

    private double calculateVolume(short[] buffer, int readSize) {
        // 方法1：峰值检测
        double maxAmplitude = 0;
        for (int i = 0; i < readSize; i++) {
            maxAmplitude = Math.max(maxAmplitude, Math.abs(buffer[i]));
        }
        double peakVolume = maxAmplitude / 32768.0;

        // 方法2：RMS（均方根）检测
        double sumSquares = 0;
        for (int i = 0; i < readSize; i++) {
            sumSquares += buffer[i] * buffer[i];
        }
        double rmsVolume = Math.sqrt(sumSquares / readSize) / 32768.0;

        // 使用两者的加权平均，更关注峰值
        return Math.max(peakVolume, rmsVolume * 1.5);
    }

    private boolean isValidClap() {
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastClapTime > CLAP_COOLDOWN_MS) {
            lastClapTime = currentTime;
            return true;
        }
        return false;
    }

    private void onClapDetected() {
        settingBean = AppSpUtils.getSetting();

        // 播放选中的铃声
        playSelectedSound();

        // 开始持续震动
        if (settingBean.isVibration()) {
            startVibrating();
        }

        // 开始闪光灯
        if (settingBean.isFlashlight()) {
            startFlashing();
        }

        // 根据duration设置停止时间
        long stopDelay = settingBean.getDuration();
        if (stopDelay == 0) {
            // duration为0时持续响铃，不自动停止
            return;
        }

        mainHandler.postDelayed(() -> {
            audioPlayer.stop();
            stopFlashing();
            stopVibrating();
        }, stopDelay);
    }

    private void playSelectedSound() {
        int soundResId = AppSpUtils.getSetting().getRing();
        if (soundResId != 0) {
            Uri uri = Uri.parse("android.resource://" + AppUtils.getAppPackageName() + "/" + soundResId);
            audioPlayer.play(UriUtils.uri2File(uri).getPath());
        }
    }

    @SuppressLint("MissingPermission")
    private void vibrate() {
        if (vibrator == null || !vibrator.hasVibrator()) {
            ToastUtils.showShort("设置暂不支持震动");
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            vibrator.vibrate(VibrationEffect.createWaveform(
                    new long[]{0, 200, 100, 200, 100, 200}, -1));
        } else {
            vibrator.vibrate(new long[]{0, 200, 100, 200, 100, 200}, -1);
        }
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "拍手检测服务",
                    NotificationManager.IMPORTANCE_LOW
            );
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
    }

    private void startFlashing() {
        if (isFlashing) return;

        isFlashing = true;
        long openTime = settingBean.getOpenTime();
        long closeTime = settingBean.getCloseTime();

        flashRunnable = new Runnable() {
            @Override
            public void run() {
                if (!isFlashing) return;

                FlashlightUtils.getInstance().startFlash();

                flashHandler.postDelayed(() -> {
                    if (!isFlashing) return;

                    FlashlightUtils.getInstance().stopFlash();

                    if (isFlashing) {
                        flashHandler.postDelayed(this, closeTime);
                    }
                }, openTime);
            }
        };

        flashHandler.post(flashRunnable);
    }

    private void stopFlashing() {
        isFlashing = false;
        if (flashHandler != null && flashRunnable != null) {
            flashHandler.removeCallbacks(flashRunnable);
        }
        FlashlightUtils.getInstance().stopFlash();
    }

    @SuppressLint("MissingPermission")
    private void startVibrating() {
        if (isVibrating) return;
        if (vibrator == null || !vibrator.hasVibrator()) {
            ToastUtils.showShort("设置暂不支持震动");
            return;
        }

        isVibrating = true;
        
        vibrateRunnable = new Runnable() {
            @Override
            public void run() {
                if (!isVibrating) return;
                
                // 震动200ms，停300ms，形成有频率的震动
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    vibrator.vibrate(VibrationEffect.createOneShot(200, VibrationEffect.DEFAULT_AMPLITUDE));
                } else {
                    vibrator.vibrate(200);
                }
                
                // 500ms后再次震动
                if (isVibrating) {
                    vibrateHandler.postDelayed(this, 500);
                }
            }
        };
        
        vibrateHandler.post(vibrateRunnable);
    }

    private void stopVibrating() {
        isVibrating = false;
        if (vibrateHandler != null && vibrateRunnable != null) {
            vibrateHandler.removeCallbacks(vibrateRunnable);
        }
        if (vibrator != null) {
            vibrator.cancel();
        }
    }

    private Notification createNotification() {
        Intent notificationIntent = new Intent(this, SoundActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);

        return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("拍手找手机")
                .setContentText("正在监听拍手声音...")
                .setSmallIcon(R.drawable.icon_dog)
                .setContentIntent(pendingIntent)
                .build();
    }
}